package com.hjx.windowtool.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.swing.JComponent;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mozilla.universalchardet.UniversalDetector;

public class JsoupTorrentSearch {
	public static String User_Agent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
	public static String Cookie = "__cfduid=d98032e80b2bdb1907c9b21174ebd2cff1561538030; __guid=121323021.3190308429754498600.1561538030921.5017; cf_clearance=9a951605127ee12810d46bbd29a89d76be66ecbd-1561539544-1800-250; monitor_count=2; UM_distinctid=16b93028bd84bf-0c32e1c2102858-3c604504-1fa400-16b93028bd9a2; CNZZDATA1261861923=428041959-1561535955-null%7C1561535955; CNZZDATA1277219225=1228724449-1561538570-null%7C1561538570; Hm_lvt_68d5318f5f5970d4fc730fd89e5ec7aa=1561539547; Hm_lpvt_68d5318f5f5970d4fc730fd89e5ec7aa=1561539547; Hm_lvt_f75b813e9c1ef4fb27eaa613c9f307b2=1561539547; Hm_lpvt_f75b813e9c1ef4fb27eaa613c9f307b2=1561539547; __atuvc=1%7C26; __atuvs=5d1333da04ff9626000";
	public static final Map<String, String> jsoupHeader=new HashMap<>();
	static{
//		jsoupHeader.put("Cookie", Cookie);
		jsoupHeader.put("If-Modified-Since", new Date().toString());
		jsoupHeader.put("Cache-Control", "max-age=0");
		jsoupHeader.put("Upgrade-Insecure-Requests", "1");
		jsoupHeader.put("User-Agent", User_Agent);
	}
	public static void main(String[] args) throws IOException {
		String s = getMegnetByCntorrentkitty("复仇者联盟3 无限战争");
		System.out.println(s);
//		System.out.println("================================================");
//		String string = getMegnetByBtyunsou("复仇者联盟3 无限战争");
//		System.out.println(string);
//		System.out.println("================================================");
//		String string2 = getMegnetByBtFeifeibt("复仇者联盟4");
//		System.out.println(string2);
	}

	/**
	 * @throws IOException
	 */
	public static String getMegnetByBtFeifeibt(String search) throws IOException {
		Connection conn = Jsoup.connect("http://feifeibtcn.cc/");
		conn.header("User-Agent", User_Agent);
		Document d = conn.data("keyword", search).post();
		
		Elements select = d.select(".search-option").select("a");
		if (select.isEmpty()) {
			return null;
		}
		String url = select.get(3).absUrl("href");
		conn = Jsoup.connect(url);
		conn.header("User-Agent",User_Agent);
		d = conn.get();
//		System.out.println(d);
		
		select = d.select(".content").select("dl[class=list-con]");
		String detailUrl=null;
		int fileSize=999999;
		for (int i = 0; i < select.size(); i++) {
			Element e = select.get(i);
			Elements select2 = e.select("span");
			for (Element element : select2) {
				if (element.text().contains("文件数")) {
					Integer valueOf = Integer.valueOf(element.text().split(":")[1]);
					if (valueOf<fileSize) {
						fileSize=valueOf;
						detailUrl=e.select("a").get(0).absUrl("href");
					}
				}
			}
		}
		System.out.println(detailUrl);
		d = conn.url(detailUrl).get();
//		System.out.println(d);
		String text = d.select(".magnet").select("a").get(0).text();
		return text.split("&")[0];
	}
	
	public static String getEncoding(byte[] bytes) {
        String defaultEncoding = "UTF-8";
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(bytes, 0, bytes.length);
        detector.dataEnd();
        String encoding = detector.getDetectedCharset();
        detector.reset();
        System.out.println("字符编码是："+encoding);
        if (encoding == null) {
            encoding = defaultEncoding;
        }
        return encoding;
    }
	
	/**
	 * 获取网页<a href="http://www.btyunsou.co/">http://www.btyunsou.co/</a>  的磁力链
	 * @param url
	 * @throws IOException
	 */
	public static String getMegnetByBtyunsou(String searchName) throws IOException {
		String url = "http://www.btyunsou.co/search/" + URLEncoder.encode(searchName, "UTF-8") + "_click_1.html";
		Connection con = Jsoup.connect(url);
		con.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
		Document document = con.get();
//		 System.out.println(document);
		Element element = document.select("div[class=media-body]").first();
		if (element!=null) {
			String s = element.select("h4").select("a[href]").first().text();
			// System.out.println(element.select("span[class=media-down]").first());
			String absUrl = element.select("span[class=media-down]").first().select("a[href]").first().attr("href");
			String megnet = absUrl.substring(absUrl.lastIndexOf("/") + 1);
			System.out.println(s + "===" + megnet);
			return "magnet:?xt=urn:btih:"+megnet.substring(0, megnet.length()-5).toLowerCase();
			
		}
		return null;
	}

	/**
	 * 百度云防护不知道怎么绕过
	 * @throws IOException
	 */
	public static String getMegnetByCntorrentkitty(String searchName) throws IOException {
		String url="http://torrentkittyla.ws/tk/"+URLEncoder.encode(searchName, "UTF-8")+"/1-4-0.html";
		
		Connection con = Jsoup.connect(url);
		con.headers(jsoupHeader);
		System.out.println(url);
		Document doc = con.get();
//		System.out.println(doc);
//		System.out.println(doc.select("div[class=list]"));
		Elements elements = doc.select("div[class=list]").select("p[class*=attr]");
		String megnet = null;
		String name="";
		if (elements.first()!=null) {
			System.out.println(elements.first());
			String absUrl = elements.first().getElementsByTag("a").get(0).absUrl("href");
			System.out.println(megnet=getMegnet(absUrl).split("&")[0]);
		}
		return megnet;
	}

	private static String getMegnet(String url) throws IOException {
		Connection con = Jsoup.connect(url);
		con.headers(jsoupHeader);
		Document doc = con.get();
//		System.out.println(doc);
		Element select = doc.select("p[class*=magnet]").first();
		String megnet = select.select("a[href]").first().attr("href");
//		System.out.println(megnet);
		return megnet;
	}
	public static void loadJsoupHeader() {
		try {
			List<String> list = Files.readAllLines(Paths.get("JsoupHeader.txt"));
			for (String string : list) {
				String[] split = string.split(":");
				jsoupHeader.put(split[0], split[1]);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
